package cn.kgc.controller;

import cn.kgc.entity.Categroy;
import cn.kgc.service.CategroyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Controller
public class CategroyController {
    @Autowired
    private CategroyService categroyService;

    @GetMapping("/cate")
    public String getAllCategroy(Model model){
        List<Categroy> lists =categroyService.getAllCategroy();
        model.addAttribute("lists",lists);
        return "categroylist";
    }
    @GetMapping("/cate/{id}")
    public String getCategroyById(@PathVariable("id")Integer id,Model model){
        Categroy categroy=categroyService.getCategroyById(id);
        model.addAttribute("categroy",categroy);
        return "categroy";
    }
    @PostMapping("/cate")
    public String addCategroy(@Valid Categroy categroy,BindingResult bindingResult){
        if (bindingResult.getErrorCount()>0) {
            return "categroy";
        }
        else {
            categroyService.addCategroy(categroy);
            return "redirect:/cate";
        }
    }
    @PutMapping("/cate")
    public String updateCategroy(@Valid Categroy categroy,BindingResult bindingResult,Model model){
        if (bindingResult.getErrorCount()>0) {
            model.addAttribute("categroy", new Categroy());
            return "categroy";
        }
        else {
            categroyService.updateCategroy(categroy);
            return "redirect:/cate";
        }
    }
    @DeleteMapping("/cate/{id}")
    public String deleteCategroyById(@PathVariable("id")Integer id){

        categroyService.deleteCategroyById(id);
        return "redirect:/cate";
    }
    @GetMapping("/cate/view")
    public String toAdvice(Model model){
        model.addAttribute("categroy",new Categroy());
        return "categroy";
    }
}
